package com.itheima.controller;

import com.itheima.common.JsonResult;
import com.itheima.pojo.admin.Dish;
import com.itheima.pojo.admin.Flavors;
import com.itheima.pojo.admin.FlavorsById;
import com.itheima.pojo.admin.Pagination;
import com.itheima.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author ChenJunJie
 * @date 2022/6/14 14:30
 * 菜品的controller层
 */
@RestController
@RequestMapping(value = "/dish", produces = "application/json;charset=utf-8")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 新增菜品
    @PostMapping
    public JsonResult<String> dishAdd(@RequestBody Dish<Flavors> dish, HttpServletRequest request) {

        return dishService.dishAdd(dish, request);
    }

    // 菜品分页查询
    @GetMapping("/page")
    public JsonResult<Pagination<Dish<Flavors>>> dishPagination(String name, @RequestParam("page") Integer page, @RequestParam("pageSize") Integer pageSize, String type) {

        return dishService.dishPagination(name, page, pageSize, type);

    }

    //通过id查询菜品
    @GetMapping("/{id}")
    public JsonResult<Dish<FlavorsById>> dishSelectById(@PathVariable String id) {
        return dishService.dishSelectById(id);
    }

    //通过菜品id修改菜品
    @PutMapping
    public JsonResult<String> dishUpdateById(@RequestBody Dish<Flavors> dish, HttpServletRequest request) {
        return dishService.dishUpdateById(dish, request);
    }

    //通过菜品id删除
    @DeleteMapping
    public JsonResult<String> flavorsDeleteById(@RequestParam("ids") String ids) {

        return dishService.dishDeleteById(ids);
    }

    //菜品下拉列表
    @GetMapping("/list")
    public JsonResult<List<Dish<FlavorsById>>> dishSelectByCategoryId(String categoryId) {
        return dishService.dishSelectByCategoryId(categoryId);
    }

    //通过菜品id修改状态
    @PostMapping("/status/{status}")
    public JsonResult<String> dishUpdateStatusById(@RequestParam("ids") String id, @PathVariable Integer status) {


        //如果有多条id，分割其逗号
        String[] split = id.split(",");

        int count = 0;
        for (String s : split) {
            int i = dishService.dishUpdateStatusById(s, status);
            count = count + i;
        }
        if (count == split.length) {
            return JsonResult.success("修改成功");
        } else {
            return JsonResult.error("修改失败");
        }

    }
}
